let gulp = require('gulp');
let gulpFileInclude = require('gulp-file-include');
let webpackStream = require('webpack-stream');
let webpack = require('webpack');
let webpackConfig = require('./webpack.config.js');
let clean = require('gulp-clean');
let sass = require('gulp-sass');
let sourceMap = require('gulp-sourcemaps');
let autoprefixer = require('gulp-autoprefixer');
let rev = require('gulp-rev');
let revCollector = require('gulp-rev-collector');
let replace = require('gulp-replace');
let minifyImg = require('gulp-imagemin');
let imageminJpegRecompress = require('imagemin-jpeg-recompress');
let imageminOptipng = require('imagemin-optipng');
let connect = require('gulp-connect');
let gulpopen = require('gulp-open');
let os = require('os');
let gulpSequence = require('gulp-sequence');

let file = {
    entry: {
        html: './src/*.html',
        scss: './src/scss/*.scss',
        js: './src/js/main.js',
        img: './src/assets/images/*',
        upload: './src/assets/upload/*'
    },
    output: {
        html: './dist/*.html',
        css: './dist/css/*.css',
        js: './dist/js/*.js',
        img: './dist/assets/images/*',
        upload: './dist/assets/upload/*'
    },
    tmp: {
        html: './tmp/*.html',
        css: './tmp/css/*.css',
        js: './tmp/js/*',
        img: './tmp/assets/images/*',
        upload: './tmp/assets/upload/*',
        rev: './tmp/**/*.json'
    }
};

let src = {
    entry: {
        html: './src/',
        scss: './src/scss/',
        js: './src/js/',
        img: './src/assets/images/',
        upload: './src/assets/upload/'
    },
    output: {
        html: './dist',
        css: './dist/css',
        js: './dist/js',
        img: './dist/assets/images',
        upload: './dist/assets/upload'
    },
    tmp: {
        html: './tmp/',
        css: './tmp/css/',
        js: './tmp/js/',
        img: './tmp/assets/images/',
        upload: './tmp/assets/upload/',
        rev: './tmp/rev/'
    }
};

let browser = os.platform() === 'linux' ? 'google-chrome' : ( //判断调用系统浏览器
    os.platform() === 'darwin' ? 'google chrome' : (
        os.platform() === 'win32' ? 'chrome' : 'chrome'
    )
);

let host = {
    host: '10.0.0.73',
    path: 'tmp/',
    port: 8081,
    index: 'index.html'
};

let minifyJpg = imageminJpegRecompress({ // jpg压缩
        accurate: true, //高精度模式
        quality: "high", //图像质量:low, medium, high and veryhigh;
        method: "smallfry", //网格优化:mpe, ssim, ms-ssim and smallfry;
        min: 70, //最低质量
        loops: 0, //循环尝试次数, 默认为6;
        progressive: false, //基线优化
        subsample: "default" //子采样:default, disable;
    }),
    minifyPng = imageminOptipng({ // png压缩
        optimizationLevel: 4
    });

// 生成暂存区
gulp.task('dev', gulpSequence(['sass', 'img', 'webpack', 'gulpFileInclude'], 'server', 'watch'));
// 生产打包
gulp.task('build', gulpSequence('clean:dist', ['sass', 'img', 'webpack', 'gulpFileInclude', 'copy:ico'], 'version', 'clean:tmp'));
// 清理
gulp.task('clean', ['clean:dist', 'clean:tmp']);

gulp.task('watch', function () {
    gulp.watch('./src/**/*', ['sass', 'img', 'webpack', 'gulpFileInclude']);
});

gulp.task('clean:dist', function () {
    return gulp.src(src.output.html)
        .pipe(clean());
});

gulp.task('clean:tmp', function () {
    return gulp.src(src.tmp.html)
        .pipe(clean());
});

gulp.task('img', ['minifyImg', 'minifyUpload']);

gulp.task('copy:ico', function () {
    return gulp.src('./src/*.ico')
        .pipe(gulp.dest(src.output.html));
});

gulp.task('minifyImg', function () { // 压缩图片
    return gulp.src(file.entry.img)
        .pipe(minifyImg({
            use: [minifyJpg, minifyPng],
            progressive: false
        }))
        .pipe(gulp.dest(src.tmp.img));
});

gulp.task('minifyUpload', function () {
    return gulp.src(file.entry.upload)
        .pipe(minifyImg({
            use: [minifyJpg, minifyPng],
            progressive: false
        }))
        .pipe(gulp.dest(src.tmp.upload));
});

gulp.task('copy:upload', function () {
    return gulp.src(file.tmp.upload)
        .pipe(gulp.dest(src.output.upload));
});

gulp.task('sass', function () {
    return gulp.src(file.entry.scss)
        .pipe(sourceMap.init())
        .pipe(sass({
            outputStyle: 'compressed'
        }).on('error', sass.logError))
        .pipe(autoprefixer({
            browsers: ['last 2 version', 'ff >= 20', 'safari 5', 'ie 9', 'opera 12.1', 'ios 6', 'android 4'],
            cascade: true, // 美化属性值
            remove: true // 去除不必要的前缀
        }))
        .pipe(sourceMap.write('./'))
        .pipe(gulp.dest(src.tmp.css));
});

gulp.task('webpack', function () { // 调用webpack打包js模块
    return gulp.src(file.entry.js)
        .pipe(webpackStream(webpackConfig, webpack))
        .pipe(gulp.dest(src.tmp.js));
});

gulp.task('gulpFileInclude', function () { // 合并html文件
    return gulp.src(file.entry.html)
        .pipe(gulpFileInclude({
            prefix: '@@',
            basepath: '@file'
        }))
        .pipe(gulp.dest(src.tmp.html));
});

gulp.task('ver_img', function () {
    return gulp.src(file.tmp.img)
        .pipe(rev())
        .pipe(gulp.dest(src.output.img))
        .pipe(rev.manifest())
        .pipe(gulp.dest('./tmp/rev/rev-img'));
});

gulp.task('link_img', ['ver_img'], function () {
    return gulp.src([file.tmp.rev, file.tmp.css])
        .pipe(revCollector())
        .pipe(gulp.dest(src.tmp.css));
});

gulp.task('ver_css', ['link_img'], function () {
    return gulp.src(file.tmp.css)
        .pipe(rev())
        .pipe(gulp.dest(src.output.css))
        .pipe(rev.manifest())
        .pipe(gulp.dest('./tmp/rev/rev-css'));
});

gulp.task('ver_js', function () {
    return gulp.src(file.tmp.js)
        .pipe(rev())
        .pipe(gulp.dest(src.output.js))
        .pipe(rev.manifest())
        .pipe(gulp.dest('./tmp/rev/rev-js'));
});

gulp.task('version', ['ver_css', 'ver_js', 'copy:upload'], function () {
    return gulp.src([file.tmp.rev, file.tmp.html])
        .pipe(revCollector({
            replaceReved: true
        }))
        .pipe(gulp.dest(src.output.html));
});

gulp.task('connect', function () { //起web服务
    console.log('网络连接中......')
    connect.server({
        host: host.host,
        root: host.path,
        port: host.port,
        livereload: true //是否开启热刷新
    })
});

gulp.task('server', ['connect'], function () {
    return gulp.src('')
        .pipe(gulpopen({
            app: browser,
            uri: `http://${host.host}:${host.port}/${host.index}`
        }))
});